// eval 注入脚本的代码,变量尽量使用var,后来发现在import之后,let会自动变为var
export default function() {
	let msgType = {
		nodeInfo: 2, //节点信息
		nodeListInfo: 1, // 节点列表信息
		notSupport: 0, // 不支持的游戏
	};
	let postData = {
		scene: {
			name: "",
			children: []
		},
	};
	window.inspectorGameMemoryStorage = window.inspectorGameMemoryStorage || {};

// slot start ---------------------------------------------------------
	window.queryLanguageKey = function(key){
		if (game){
			console.log(`key=> `,game.LanguageManager.getInstance().getDstStr(key));
		}
	};
	window.pluginPlayPrize = function(){
		slot.WinAniManager.instance.playWinAni(4, 666666666666, slot.Handler.create(this,()=>{}))
	};
	
	// 收集节点信息
	function getRollNode(node,name) {
		let tagNode = node.getComponent(name);
	    if (tagNode) {
	        return node;
	        // return tagNode.rollerLayer;
	    }
	    let nodeChildren = node.getChildren();
	    for (let i = 0; i < nodeChildren.length; i++) {
	        let result = getRollNode(nodeChildren[i],name);
	        if (result) {
	            return result; // 如果找到了符合条件的节点，直接返回
	        }
	    }
	    return null; // 如果没有找到，则返回 null
	}
	window.pluginLookNode = function(name){
		let scene = cc.director.getScene();
		if (scene) {
			let rollNode = null;
			let _nodes = scene.getChildren();
			for (let i = 0; i < _nodes.length; i++) {
				let node = _nodes[i];
				let foundNode = getRollNode(node,name); // 调用 getRollNode 函数获取符合条件的节点
				if (foundNode) {
					rollNode = foundNode; // 如果找到了符合条件的节点，赋值给 rollNode
					break; // 停止循环，因为已经找到了符合条件的节点
				}
			}
			if (!rollNode){
				return;
			}
			postData.scene = {
				type: 1, // 标识类型
				uuid: rollNode.uuid,
				name: rollNode.name,
				children: [],
				active: false,
			};
			window.inspectorGameMemoryStorage[rollNode.uuid] = rollNode;

			let sceneChildren = rollNode.getChildren();
			for (let i = 0; i < sceneChildren.length; i++) {
				let node = sceneChildren[i];
				getNodeChildren(node, postData.scene.children);
			}
			// console.log('postData',postData);
			window.sendMsgToDevTools(msgType.nodeListInfo, postData);
		} else {
			postData.scene = null;
			// console.log("不支持调试游戏");
			window.sendMsgToDevTools(msgType.notSupport, "不支持调试游戏!");
		}
	};
	// 打印滚轴结果
	window.rollingResultLog = function(){
		if (slot){
			console.log("[cocos-creator-inspector]=>【slot.SpinManager.instance.rollingResult】", slot.SpinManager.instance.rollingResult);
		}
	}
// slot end ---------------------------------------------------------
	
	
	
	window.pluginLocalhost = function(uuid, key, value,isNumber) {
		window.open(`http://localhost:7456${window.location.search}`,"_self");
	};
	
	window.pluginSetMaskData = function(uuid, key, value,isNumber) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent(cc.Mask);
			if (com) {
				let _value = value;
				if (value == 'true') _value = true;
				if (value == 'false') _value = false;
				if (isNumber == 'true') _value = Number(value);
				com[key] = _value;
			}
		}
	};
	window.pluginSetNodeSpriteFillCenter = function(uuid, x, y) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent(cc.Sprite);
			if (com) {
				com.fillCenter = cc.v3(Number(x),Number(y));
			}
		}
	};
	window.pluginSetNodeBlockInputEnabled = function(uuid, value) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent(cc.BlockInputEvents);
			if (com) {
				com.enabled = value == 'true' ? true : false;
			}
		}
	};
	window.pluginSetNodeSkeletonData = function(uuid, key, value,isNumber) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent(sp.Skeleton);
			if (com) {
				let _value = value;
				if (value == 'true') _value = true;
				if (value == 'false') _value = false;
				if (isNumber == 'true') _value = Number(value);
				com[key] = _value;
			}
		}
	};
	window.pluginPlaysSkeleton = function(uuid, isLoop, name) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent(sp.Skeleton);
			if (com) {
				com.setAnimation(0,name,isLoop == 'true' ? true : false);
			}
		}
	};
	window.pluginPlayAnimation = function(uuid, isLoop, name) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent(cc.Animation);
			if (com) {
				com.play(name).wrapMode = isLoop == 'true' ? cc.WrapMode.Loop : cc.WrapMode.Normal;
			}
		}
	};
	
	window.pluginLog = function(value) {
		console.log("[cocos-creator-inspector]=>", value);
	};
	window.pluginSetGamePause = function(value) {
		if(value == 'true'){
			cc.director.pause();
		}else{
			cc.director.resume();
		}
	};
	window.pluginSetMControllerData = function(uuid,  value) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent('MController');
			if (com) com.stateIndex = Number(value);
		}
	};
	window.pluginSetNodeSpriteData = function(uuid, key, value,isNumber) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent(cc.Sprite);
			if (com) {
				let _value = value;
				if (value == 'true') _value = true;
				if (value == 'false') _value = false;
				if (isNumber == 'true') _value = Number(value);
				com[key] = _value;
			}
		}
	};
	
	// 游戏设置 ---------------------------------------------------------
	window.setSlowMotion= function(value) {
		cc.director.getScheduler().setTimeScale(Number(value));
		sp.timeScale = Number(value);
	}
	// 游戏设置 ---------------------------------------------------------
	
	// 设置cc.Label ---------------------------------------------------------
	/**
	 * 设置Label  值，方向,
	 * @param uuid 唯一标识
	 * @param key key值
	 * @param value 值
	 * @param isNumber 是否数字类型
	 */
	window.pluginSetNodeLabelData = function(uuid, key, value,isNumber) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let com = node.getComponent(cc.Label);
			if (com) {
				let _value = value;
				if (value == 'true') _value = true;
				if (value == 'false') _value = false;
				if (isNumber == 'true') _value = Number(value);
				com[key] = _value;
			}
		}
	};
	
	// 设置cc.Label ---------------------------------------------------------
	window.pluginSetNodeColor = function(uuid, value) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			var color = cc.Color.BLACK;
			color.fromHEX(value);
			node.color = color;
		}
	};
	window.pluginSetNodeData = function(uuid, key, value,isNumber) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let _value = isNumber == 'true' ? Number(value) : value;
			node[key] = _value;
		}
	};
	// 设置节点是否可视
	window.pluginSetNodeActive = function(uuid, isActive) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			if (isActive === 1) {
				node.active = true;
			} else if (isActive === 0) {
				node.active = false;
			}
		}
	};
	/** 打印节点 */
	window.logNodeInfo = function(uuid) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			console.log("[cocos-creator-inspector]=>", node);
		}
	}
	// 收集组件信息
	function getNodeComponentsInfo(node) {
		let ret = [];
		let nodeComp = node._components;
		for (let i = 0; i < nodeComp.length; i++) {
			let itemComp = nodeComp[i];
			window.inspectorGameMemoryStorage[itemComp.uuid] = itemComp;
			ret.push({
				uuid: itemComp.uuid,
				type: itemComp.constructor.name,
				name: itemComp.name,
			});
		}
		return ret;
	}

	// 获取节点信息
	window.getNodeInfo = function(uuid) {
		let node = window.inspectorGameMemoryStorage[uuid];
		if (node) {
			let labelData = null;
			let mControllerIndex = null;
			let animationClips = null;
			let blockInputData = null;
			let spriteData = null;
			let skeletonData = null;
			let maskData = null;
			if (node._components.length > 0) {
				// cc.Label
				let labelCom = node.getComponent(cc.Label);
				if (labelCom) {
					labelData = {
						enabled: labelCom.enabled,
						string: labelCom.string,
						horizontalAlign: labelCom.horizontalAlign,
						verticalAlign: labelCom.verticalAlign,
						fontSize: labelCom.fontSize,
						lineHeight: labelCom.lineHeight,
						overflow: labelCom.overflow,
						enableBold: labelCom.enableBold,
						enableItalic: labelCom.enableItalic,
						enableUnderline: labelCom.enableUnderline,
						cacheMode: labelCom.cacheMode,
						dstBlendFactor: labelCom.dstBlendFactor
					}
				}
				// MController
				let MControllerCom = node.getComponent('MController');
				if(MControllerCom) mControllerIndex = MControllerCom.stateIndex;
				
				// cc.Animation
				let nimationCom = node.getComponent('cc.Animation');
				if (nimationCom) {
					animationClips = [];
					let anis = nimationCom.getClips();
					for (let i = 0; i < anis.length; i++) {
						if(anis[i]) animationClips.push(anis[i].name);
					}
				}
				
				// sp.Skeleton
				let spin = node.getComponent('sp.Skeleton');
				if (spin) {
					skeletonData = {
						animations: []
					}
					if (spin.skeletonData && spin.skeletonData._skeletonCache){
						var _animations = spin.skeletonData._skeletonCache.animations;
						for (let i = 0; i < _animations.length; i++) {
							skeletonData['animations'].push(_animations[i].name);
						}
						skeletonData['premultipliedAlpha'] = spin.premultipliedAlpha;
						skeletonData['defaultSkin'] = spin.defaultSkin;
						skeletonData['defaultAnimation'] = spin.defaultAnimation;
						skeletonData['animation'] = spin.animation;
						skeletonData['loop'] = spin.loop;
						skeletonData['timeScale'] = spin.timeScale;
					}
				}
				// cc.BlockInputEvents
				let blockInputCom = node.getComponent('cc.BlockInputEvents');
				if (blockInputCom) {
					blockInputData = {
						enabled: blockInputCom.enabled
					}
				}
				
				// cc.Sprite
				let spCom = node.getComponent(cc.Sprite);
				if (spCom) {
					spriteData = {
						enabled: spCom.enabled,
						sizeMode: spCom.sizeMode,
						trim: spCom.trim,
						type: spCom.type,
						fillType: spCom.fillType,
						fillStart: spCom.fillStart,
						fillRange: spCom.fillRange,
						fillCenterX: spCom.fillCenter.x,
						fillCenterY: spCom.fillCenter.y,
						dstBlendFactor: spCom.dstBlendFactor,
						srcBlendFactor: spCom.srcBlendFactor
					}
				}
				// cc.Mask
				let maskCom = node.getComponent('cc.Mask');
				if (maskCom) {
					maskData = {
						enabled: maskCom.enabled,
						type: maskCom.type,
						inverted: maskCom.inverted,
						alphaThreshold: maskCom.alphaThreshold,
						segements: maskCom.segements
					}
				}
				

			}

			let nodeData = {
				type: node.constructor.name,
				uuid: node.uuid,
				name: node.name,
				x: node.x,
				y: node.y,
				zIndex: node.zIndex,
				width: node.width,
				height: node.height,
				color: node.color.toCSS('rgb'),
				opacity: node.opacity,
				angle: node.angle,
				anchorX: node.anchorX,
				anchorY: node.anchorY,
				scaleX: node.scaleX,
				scaleY: node.scaleY,
				skewX: node.skewX,
				skewY: node.skewY,
				labelData,
				mControllerIndex,
				animationClips,
				skeletonData,
				blockInputData,
				spriteData,
				maskData
			};
			let nodeType = node.constructor.name;
			if (nodeType === 'cc_Scene') {

			} else {
				nodeData.active = node.active;
			}
			window.sendMsgToDevTools(msgType.nodeInfo, nodeData);
		} else {
			// 未获取到节点数据
			// console.log("未获取到节点数据");
		}
	};

	// 收集节点信息
	function getNodeChildren(node, data) {
		let isBlockInput = false;
		if (node._components.length > 0 && node.getComponent(cc.BlockInputEvents)) {
			// console.error('isBlockInput');
			isBlockInput =  true;
		}
		
		let nodeData = {
			uuid: node.uuid,
			name: node.name,
			active: node.active,
			children: [],
			isBlockInput
		};
		window.inspectorGameMemoryStorage[node.uuid] = node;
		let nodeChildren = node.getChildren();
		for (let i = 0; i < nodeChildren.length; i++) {
			let childItem = nodeChildren[i];
			getNodeChildren(childItem, nodeData.children);
		}
		data.push(nodeData);
	}

	window.sendMsgToDevTools = function(type, msg) {
		window.postMessage({
			type: type,
			msg: msg
		}, "*");
	};
	
	// 检测是否包含cc变量
	let isCocosCreatorGame = true;
	try {
		let cocosInspectorTestVar = cc;
	} catch (e) {
		isCocosCreatorGame = false;
		window.sendMsgToDevTools(msgType.notSupport, "不支持调试游戏!");
	}

	if (isCocosCreatorGame) {
		let scene = cc.director.getScene();
		if (scene) {
			postData.scene = {
				type: 1, // 标识类型
				uuid: scene.uuid,
				name: scene.name,
				children: [],
				active: false,
			};
			window.inspectorGameMemoryStorage[scene.uuid] = scene;

			let sceneChildren = scene.getChildren();
			for (let i = 0; i < sceneChildren.length; i++) {
				let node = sceneChildren[i];
				getNodeChildren(node, postData.scene.children);
			}
			// console.log('postData',postData);
			window.sendMsgToDevTools(msgType.nodeListInfo, postData);
		} else {
			postData.scene = null;
			// console.log("不支持调试游戏");
			window.sendMsgToDevTools(msgType.notSupport, "不支持调试游戏!");
		}
	} else {
		// console.log("未发现cocos creator game");
	}
}